package crawler.web.berkeleydb;

import java.io.File;
import java.util.Iterator;

import library.database.mongo.ObjectId;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.StoreConfig;

import crawler.web.beans.PageFingerPrint;

public class SimpleStoreGet {

	private static File envHome = new File("source/crawler/berkeleydb/3");

	private Environment envmnt;
	private EntityStore store;
	private SimpleDA sda;

	//Next we create a method that simply opens our database environment and entity store for us.

	// The setup() method opens the environment and store
	// for us.
	public void setup() throws DatabaseException {

		EnvironmentConfig envConfig = new EnvironmentConfig();
		StoreConfig storeConfig = new StoreConfig();

		envConfig.setAllowCreate(true);
		storeConfig.setAllowCreate(true);
		envHome.mkdirs();
		// Open the environment and entity store
		envmnt = new Environment(envHome, envConfig);
		store = new EntityStore(envmnt, "EntityStore", storeConfig);

	}

	//We also need a method to close our environment and store.

	// Close our environment and store.
	public void shutdown() throws DatabaseException {
		store.close();
		envmnt.close();
	}

	//Now we retrieve a few objects. To do this, we instantiate a SimpleDA (see SimpleDA.class) class that we use to access our primary and secondary indexes. Then we retrieve objects based on a primary or secondary index value. And finally, we display the retrieved objects.

	// Retrieve some SimpleEntityClass objects from the store.
	private void run() throws DatabaseException {

		setup();

		// Open the data accessor. This is used to store
		// persistent objects.
		sda = new SimpleDA(store);

		EntityCursor<PageFingerPrint> entities = sda.sIdx.subIndex("bbss").entities();
		Iterator<PageFingerPrint> it = entities.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());

		}
		entities.close();

		System.out.println("---------all---------");

		// Instantiate and store some entity classes
		EntityCursor<ObjectId> keys = sda.pIdx.keys();
		for (ObjectId k : keys) {
			PageFingerPrint sec1 = sda.pIdx.get(k);
			System.out.println("sec1: " + sec1);
		}
		keys.close();

		shutdown();
	}

	//Finally, to complete our class, we need a main() method, which simply calls our run() method.

	// main
	public static void main(String args[]) {
		SimpleStoreGet ssg = new SimpleStoreGet();
		try {
			ssg.run();
		} catch (DatabaseException dbe) {
			System.err.println("SimpleStoreGet: " + dbe.toString());
			dbe.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception: " + e.toString());
			e.printStackTrace();
		}
		System.out.println("All done.");
	}

}
